//
//  ViewController.m
//  ZipTest
//
//  Created by Brandon Trebitowski on 8/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "ZipArchive.h"
#import "DownLoadManager.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#define DocumentsDirectory [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0]
@interface ViewController ()
{
    AVAudioPlayer *_player;
}
@end

@implementation ViewController

@synthesize imageView = _imageView;
@synthesize label = _label;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *zipPath = [path stringByAppendingPathComponent:@"zip.zip"];
    DownLoadManager *down = [DownLoadManager sharedDownLoadManager];
    down.localPath = zipPath;
    [down beginDownload];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(unzip) name:@"downloadHasFinished" object:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//
//    dispatch_queue_t queue = dispatch_get_global_queue(
//                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_async(queue, ^{
//        NSURL *url = [NSURL URLWithString:@"http://192.168.1.46/zip.zip"];
//        NSError *error = nil;
//        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
//        
//        if(!error)
//        {        
//            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//            NSString *path = [paths objectAtIndex:0];
//            NSString *zipPath = [path stringByAppendingPathComponent:@"zipfile.zip"];
//
//            [data writeToFile:zipPath options:0 error:&error];
//            
//            if(!error)
//            {
//                ZipArchive *za = [[ZipArchive alloc] init];
//                if ([za UnzipOpenFile: zipPath])
//                {
//                    BOOL ret = [za UnzipFileTo: path overWrite: YES];
//                    if (NO == ret){} [za UnzipCloseFile];
//                    NSLog(@"解压缩成功");
//                }
//            }
//            else
//            {
//                NSLog(@"Error saving file %@",error);
//            }
//        }
//        else
//        {
//            NSLog(@"Error downloading zip file: %@", error);
//        }
//        
//    });
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (IBAction)zipFilesButtonPressed:(id)sender
{
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *docspath = [paths objectAtIndex:0];
//    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *cachePath = [paths objectAtIndex:0];
//    
//    NSString *zipFile = [docspath stringByAppendingPathComponent:@"newzipfile.zip"];
//    
//    ZipArchive *za = [[ZipArchive alloc] init];
//    [za CreateZipFile2:zipFile];
//    
//    NSString *imagePath = [cachePath stringByAppendingPathComponent:@"photo.png"];
//    NSString *textPath = [cachePath stringByAppendingPathComponent:@"text.txt"];
//    
//    [za addFileToZip:imagePath newname:@"NewPhotoName.png"];
//    [za addFileToZip:textPath newname:@"NewTextName.txt"];
//    
//    BOOL success = [za CloseZipFile2];
//    
//    NSLog(@"Zipped file with result %d",success);
    
}


- (void)unzip
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *zipPath = [path stringByAppendingPathComponent:@"zip.zip"];
    ZipArchive *za = [[ZipArchive alloc] init];
    if ([za UnzipOpenFile: zipPath])
    {
        BOOL ret = [za UnzipFileTo: path overWrite: YES];
        if (NO == ret){} [za UnzipCloseFile];
        NSLog(@"解压缩成功");
        
        NSString *musicPath = [path stringByAppendingPathComponent:@"aaaa.mp3"];
        [self createStreamerWithPath:musicPath];
    }
    else
    {
        NSLog(@"解压缩失败!!!");
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)createStreamerWithPath:(NSString *)path
{
    if (_player == nil)
    {
        _player = [[AVAudioPlayer alloc] init];
    }
    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) return;
	_player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
	if (!_player)
	{
		NSLog(@"Error: %@", [error localizedDescription]);
		return;
	}
	[_player prepareToPlay];
	[_player setNumberOfLoops:1];
    
    [_player play];
}
@end
